package com.security.config.filter;

import com.security.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    private JwtTokenUtil jwtTokenUtil;

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager,JwtTokenUtil jwtTokenUtil) {
        super(authenticationManager);
        this.jwtTokenUtil =  jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal
            (HttpServletRequest request, HttpServletResponse response,
             FilterChain chain) throws IOException, ServletException {
        System.out.println("jwtTokenUtil.getHeader()========"+jwtTokenUtil.getHeader());
        String tokenHeader = request.getHeader(jwtTokenUtil.getHeader());
        // 如果请求头中没有Authorization信息则直接放行了
        if (StringUtils.isEmpty(tokenHeader)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        String usernameFromToken = jwtTokenUtil.getUsernameFromToken(tokenHeader);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(usernameFromToken, null, null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        super.doFilterInternal(request, response, chain);
    }

}
